package de.java.shortys.utils.type;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Locale;

import de.java.shortys.utils.type.exceptions.DateFormatException;

public final class TypeUtils {

	public static Object toType(String value, Class<? extends Object> clazz, Locale locale, boolean preventExceptions) {
		if (Double.class.equals(clazz)) {
			return toDouble(value, locale, preventExceptions);
		} else if (Integer.class.equals(clazz)) {
			return toInteger(value, locale, preventExceptions);
		} else if (Calendar.class.equals(clazz)) {
			try {
				DateFormat sdf = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
				return CalendarUtils.toCalendar(sdf.parse(value));
			} catch (ParseException e) {
				if (!preventExceptions) {
					throw new DateFormatException(value);
				}
			}
		}
		return null;
	}

	public static Object toDouble(String value, Locale locale, boolean preventExceptions) {
		try {
			return DecimalFormat.getInstance(locale).parse(value).doubleValue();
		} catch (NumberFormatException e) {
			if (!preventExceptions) {
				throw e;
			}
		} catch (ParseException e) {
			if (!preventExceptions) {
				throw new NumberFormatException(e.getMessage());
			}
		}
		return null;
	}

	public static Object toInteger(String value, Locale locale, boolean preventExceptions) {
		try {
			return DecimalFormat.getInstance(locale).parse(value).intValue();
		} catch (NumberFormatException e) {
			if (!preventExceptions) {
				throw e;
			}
		} catch (ParseException e) {
			if (!preventExceptions) {
				throw new NumberFormatException(e.getMessage());
			}
		}
		return null;
	}

	private TypeUtils() {
		// Empty
	}
}
